/**
 * 小红书平台API路由
 * 处理OAuth认证、用户信息、笔记发布、数据分析等功能
 */

import { Router, Request, Response } from 'express';
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import crypto from 'crypto';
import multer from 'multer';

const router = Router();

// 小红书开放平台配置
const XIAOHONGSHU_CONFIG = {
  baseUrl: 'https://edith.xiaohongshu.com',
  apiKey: process.env.XIAOHONGSHU_API_KEY || '',
  apiSecret: process.env.XIAOHONGSHU_API_SECRET || '',
};

// 配置multer用于文件上传
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 100 * 1024 * 1024, // 100MB
  },
  fileFilter: (req, file, cb) => {
    // 允许图片和视频文件
    if (file.mimetype.startsWith('image/') || file.mimetype.startsWith('video/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片和视频文件'));
    }
  }
});

// 生成签名
function generateSignature(params: Record<string, any>, secret: string): string {
  const sortedKeys = Object.keys(params).sort();
  const queryString = sortedKeys
    .map(key => `${key}=${params[key]}`)
    .join('&');
  
  return crypto
    .createHmac('sha256', secret)
    .update(queryString)
    .digest('hex');
}

// 创建小红书API请求实例
const xiaohongshuApi = axios.create({
  baseURL: XIAOHONGSHU_CONFIG.baseUrl,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
    'User-Agent': 'BabyAI-Agent/1.0'
  }
});

// 请求拦截器
xiaohongshuApi.interceptors.request.use(
  (config: any) => {
    console.log(`Xiaohongshu API Request: ${config.method?.toUpperCase()} ${config.url}`);
    return config;
  },
  (error: any) => {
    console.error('Xiaohongshu API Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
xiaohongshuApi.interceptors.response.use(
  (response: any) => {
    console.log(`Xiaohongshu API Response: ${response.status} ${response.config.url}`);
    return response;
  },
  (error: any) => {
    console.error('Xiaohongshu API Response Error:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

/**
 * POST /api/xiaohongshu/oauth/token
 * 获取访问令牌
 */
router.post('/oauth/token', async (req: Request, res: Response) => {
  try {
    const { client_id, client_secret, code, redirect_uri, grant_type } = req.body;
    
    if (!client_id || !client_secret || !code || !redirect_uri) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    const response = await xiaohongshuApi.post('/api/oauth/token', {
      client_id,
      client_secret,
      code,
      redirect_uri,
      grant_type: grant_type || 'authorization_code'
    });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('获取小红书访问令牌失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '获取访问令牌失败'
    });
  }
});

/**
 * GET /api/xiaohongshu/user/info
 * 获取用户信息
 */
router.get('/user/info', async (req: Request, res: Response) => {
  try {
    const { access_token, user_id } = req.query;
    
    if (!access_token) {
      return res.status(400).json({
        success: false,
        msg: '缺少访问令牌'
      });
    }
    
    const params: any = { access_token };
    if (user_id) {
      params.user_id = user_id;
    }
    
    const response = await xiaohongshuApi.get('/api/sns/web/v1/user/otherinfo', { params });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('获取小红书用户信息失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '获取用户信息失败'
    });
  }
});

/**
 * GET /api/xiaohongshu/user/notes
 * 获取用户笔记列表
 */
router.get('/user/notes', async (req: Request, res: Response) => {
  try {
    const { access_token, user_id, cursor = '', num = 20 } = req.query;
    
    if (!access_token || !user_id) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    const response = await xiaohongshuApi.get('/api/sns/web/v1/user_posted', {
      params: {
        access_token,
        user_id,
        cursor,
        num: Number(num)
      }
    });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('获取小红书用户笔记失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '获取用户笔记失败'
    });
  }
});

/**
 * POST /api/xiaohongshu/note/publish
 * 发布笔记到小红书
 */
router.post('/note/publish', async (req: Request, res: Response) => {
  try {
    const { access_token, title, desc, type, images, video_url, tags, topics, location, privacy_setting } = req.body;
    
    if (!access_token || !title || !desc || !type) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    const publishData = {
      access_token,
      title,
      desc,
      type,
      images: images || [],
      video_url: video_url || '',
      tags: tags || [],
      topics: topics || [],
      location: location || null,
      privacy_setting: privacy_setting || 'public'
    };
    
    const response = await xiaohongshuApi.post('/api/media/v2/upload', publishData);
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('发布小红书笔记失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '发布笔记失败'
    });
  }
});

/**
 * GET /api/xiaohongshu/note/detail
 * 获取笔记详情
 */
router.get('/note/detail', async (req: Request, res: Response) => {
  try {
    const { access_token, note_id } = req.query;
    
    if (!access_token || !note_id) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    const response = await xiaohongshuApi.get('/api/sns/web/v1/feed', {
      params: {
        access_token,
        note_id
      }
    });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('获取小红书笔记详情失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '获取笔记详情失败'
    });
  }
});

/**
 * POST /api/xiaohongshu/data/note_analytics
 * 获取笔记数据分析
 */
router.post('/data/note_analytics', async (req: Request, res: Response) => {
  try {
    const { access_token, note_ids, date_range = '7days' } = req.body;
    
    if (!access_token || !note_ids || !Array.isArray(note_ids)) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数或参数格式错误'
      });
    }
    
    const response = await xiaohongshuApi.post('/api/creator/data/note', {
      access_token,
      note_ids,
      date_range
    });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('获取小红书笔记数据分析失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '获取数据分析失败'
    });
  }
});

/**
 * GET /api/xiaohongshu/search/notes
 * 搜索笔记
 */
router.get('/search/notes', async (req: Request, res: Response) => {
  try {
    const { access_token, keyword, sort = 'general', page = 1 } = req.query;
    
    if (!access_token || !keyword) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    const response = await xiaohongshuApi.get('/api/sns/web/v1/search/notes', {
      params: {
        access_token,
        keyword,
        sort,
        page: Number(page)
      }
    });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('搜索小红书笔记失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '搜索笔记失败'
    });
  }
});

/**
 * GET /api/xiaohongshu/topics/hot
 * 获取热门话题
 */
router.get('/topics/hot', async (req: Request, res: Response) => {
  try {
    const { access_token, category } = req.query;
    
    if (!access_token) {
      return res.status(400).json({
        success: false,
        msg: '缺少访问令牌'
      });
    }
    
    const params: any = { access_token };
    if (category) {
      params.category = category;
    }
    
    const response = await xiaohongshuApi.get('/api/sns/web/v1/topics/hot', { params });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('获取小红书热门话题失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '获取热门话题失败'
    });
  }
});

/**
 * POST /api/xiaohongshu/upload/image
 * 上传图片
 */
router.post('/upload/image', upload.single('file'), async (req: Request, res: Response) => {
  try {
    const { access_token } = req.body;
    const file = req.file;
    
    if (!access_token || !file) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数或文件'
      });
    }
    
    // 检查文件类型
    if (!file.mimetype.startsWith('image/')) {
      return res.status(400).json({
        success: false,
        msg: '只允许上传图片文件'
      });
    }
    
    const formData = new FormData();
    formData.append('file', new Blob([file.buffer], { type: file.mimetype }), file.originalname);
    formData.append('access_token', access_token);
    
    const response = await xiaohongshuApi.post('/api/media/v2/upload_image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('上传小红书图片失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '上传图片失败'
    });
  }
});

/**
 * POST /api/xiaohongshu/upload/video
 * 上传视频
 */
router.post('/upload/video', upload.single('file'), async (req: Request, res: Response) => {
  try {
    const { access_token } = req.body;
    const file = req.file;
    
    if (!access_token || !file) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数或文件'
      });
    }
    
    // 检查文件类型
    if (!file.mimetype.startsWith('video/')) {
      return res.status(400).json({
        success: false,
        msg: '只允许上传视频文件'
      });
    }
    
    const formData = new FormData();
    formData.append('file', new Blob([file.buffer], { type: file.mimetype }), file.originalname);
    formData.append('access_token', access_token);
    
    const response = await xiaohongshuApi.post('/api/media/v2/upload_video', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    res.json({
      success: true,
      data: response.data
    });
  } catch (error: any) {
    console.error('上传小红书视频失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '上传视频失败'
    });
  }
});

/**
 * POST /api/xiaohongshu/sync/user
 * 同步用户数据到本地数据库
 */
router.post('/sync/user', async (req: Request, res: Response) => {
  try {
    const { user_info, notes } = req.body;
    
    if (!user_info) {
      return res.status(400).json({
        success: false,
        msg: '缺少用户信息'
      });
    }
    
    // 这里应该将数据同步到数据库
    console.log('同步小红书用户数据:', {
      user_id: user_info.user_id,
      nickname: user_info.nickname,
      note_count: notes?.length || 0
    });
    
    // TODO: 实际的数据库同步逻辑
    // await supabase.from('xiaohongshu_users').upsert({
    //   user_id: user_info.user_id,
    //   user_data: user_info,
    //   notes: notes,
    //   updated_at: new Date().toISOString()
    // });
    
    res.json({
      success: true,
      msg: '用户数据同步成功'
    });
  } catch (error: any) {
    console.error('同步小红书用户数据失败:', error);
    res.status(500).json({
      success: false,
      msg: '同步用户数据失败'
    });
  }
});

/**
 * POST /api/xiaohongshu/schedule
 * 定时发布内容
 */
router.post('/schedule', async (req: Request, res: Response) => {
  try {
    const { content, schedule_time, access_token } = req.body;
    
    if (!content || !schedule_time || !access_token) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    // 这里应该将定时任务存储到队列中
    console.log('创建小红书定时发布任务:', {
      content: content,
      schedule_time: new Date(schedule_time).toISOString()
    });
    
    // TODO: 实际的定时任务逻辑
    // 可以使用Redis队列、数据库定时任务等方式实现
    
    res.json({
      success: true,
      msg: '定时发布任务创建成功'
    });
  } catch (error: any) {
    console.error('创建小红书定时发布任务失败:', error);
    res.status(500).json({
      success: false,
      msg: '创建定时发布任务失败'
    });
  }
});

/**
 * POST /api/xiaohongshu/content/recommendations
 * 获取内容推荐
 */
router.post('/content/recommendations', async (req: Request, res: Response) => {
  try {
    const { access_token, category, tags } = req.body;
    
    if (!access_token || !category) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    // 模拟内容推荐数据
    const recommendations = {
      trending_topics: [
        '母婴好物推荐',
        '新手妈妈必备',
        '宝宝辅食制作',
        '育儿心得分享',
        '亲子互动游戏'
      ],
      suggested_tags: [
        '#母婴',
        '#育儿',
        '#宝宝',
        '#新手妈妈',
        '#好物推荐',
        '#辅食',
        '#亲子时光'
      ],
      optimal_time: '19:00-21:00',
      content_tips: [
        '使用高质量的图片和视频',
        '标题要吸引人且包含关键词',
        '内容要有实用价值',
        '适当使用热门话题标签',
        '与粉丝积极互动'
      ]
    };
    
    res.json({
      success: true,
      data: recommendations
    });
  } catch (error: any) {
    console.error('获取小红书内容推荐失败:', error);
    res.status(500).json({
      success: false,
      msg: '获取内容推荐失败'
    });
  }
});

/**
 * GET /api/xiaohongshu/stats
 * 获取小红书账号统计数据
 */
router.get('/stats', async (req: Request, res: Response) => {
  try {
    const { access_token, user_id } = req.query;
    
    if (!access_token || !user_id) {
      return res.status(400).json({
        success: false,
        msg: '缺少必要参数'
      });
    }
    
    // 获取用户信息
    const userResponse = await xiaohongshuApi.get('/api/sns/web/v1/user/otherinfo', {
      params: { access_token, user_id }
    });
    
    // 获取用户笔记
    const notesResponse = await xiaohongshuApi.get('/api/sns/web/v1/user_posted', {
      params: { access_token, user_id, cursor: '', num: 100 }
    });
    
    const userInfo = userResponse.data.data;
    const notes = notesResponse.data.data?.notes || [];
    
    // 计算统计数据
    const totalLikes = notes.reduce((sum: number, note: any) => {
      return sum + (note.interact_info?.liked_count || 0);
    }, 0);
    
    const totalCollects = notes.reduce((sum: number, note: any) => {
      return sum + (note.interact_info?.collected_count || 0);
    }, 0);
    
    const totalComments = notes.reduce((sum: number, note: any) => {
      return sum + (note.interact_info?.comment_count || 0);
    }, 0);
    
    const avgEngagement = notes.length > 0 ? 
      (totalLikes + totalCollects + totalComments) / notes.length : 0;
    
    res.json({
      success: true,
      data: {
        user_info: userInfo,
        stats: {
          fans: userInfo.fans,
          follows: userInfo.follows,
          notes: userInfo.notes,
          total_likes: totalLikes,
          total_collects: totalCollects,
          total_comments: totalComments,
          avg_engagement: Math.round(avgEngagement),
          recent_notes: notes.slice(0, 10)
        }
      }
    });
  } catch (error: any) {
    console.error('获取小红书账号统计数据失败:', error);
    res.status(500).json({
      success: false,
      msg: error.response?.data?.msg || '获取统计数据失败'
    });
  }
});

export default router;